﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DateiaftenLibTest;

/// <summary>
/// Summary description for CityBLL
/// </summary>
public class CityBLL
{
    private static CityBLL instance;
    private DateiaftenDataContext db;
    private GeoDistance GeoDis;

    private CityBLL()
    {
        db = new DateiaftenDataContext();
        GeoDis = new GeoDistance();
    }

    public static CityBLL Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new CityBLL();
            }
            return instance;
        }
    }

    public City FindCityByNameAndZipcode(string cityname, string zipcode)
    {
        try
        {
            var city = (from c in db.Cities where c.Cityname == cityname && c.Zipcode.ToString() == zipcode select c).Take(1).SingleOrDefault();
            return city;
        }
        catch
        {
            throw new Exception("By ikke fundet");
        }
    }

    public List<City> GetAllCitys()
    {
        return (from c in db.Cities
               select c).ToList();
    }

    public List<City> FindCitysWithinDistance(City CityFrom, double radius)
    {
        var Citys = GetAllCitys();
        double slat, slon, dlat, dlon;
        List<City> citylist = new List<City>();
        slat = Convert.ToDouble(CityFrom.Latitude);
        slon = Convert.ToDouble(CityFrom.Longitude);

        foreach (var item in Citys)
        {
            dlat = Convert.ToDouble(item.Latitude);
            dlon = Convert.ToDouble(item.Longitude);
            if (dlat != 0 && dlon != 0)
            {
                if (radius >= GeoDis.distance(slat, slon, dlat, dlon))
                {
                    citylist.Add(item);
                }
            }
        }
        return citylist;
    }
}